// 云函数入口文件
const cloud = require('wx-server-sdk')
var request = require('request')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event.URL)
  //qz
  var rdata = await db.collection('QUERY_RES').where({
    url: event.URL
  }).get();
  //console.log(rdata)
  if (rdata.data.length == 0) {
    console.log('调用请求转发')
    return new Promise((resolve, reject) => {
      request({
        url: event.URL,
        method: "GET",
        json: true,
        headers: {
          "content-type": "application/json",
          "token": event.token
        },
      }, function (error, response, body) {
        //console.log(body)
        if (!error && response.statusCode == 200) {
          try {
            var malist = ['getCurrentTime','getKscx','getEarlyWarnInfo','getJxlcx','getKxJscx','getStudentIdInfo','getXnxq','getXqcx'];
            var log = false;
            for(var i=0;i<malist.length;i++){
              if(event.URL.indexOf(malist[i])!=-1){
                log = true;
                break;
              }
            }
            if(typeof(body.token)!='undefined') log = false;
            if (log) {
              console.log(event.URL+'请求数据写入数据库')
              db.collection('QUERY_RES').add({
                data: {
                  url: event.URL,
                  data: body
                }
              })
            }else{
              console.log('请求未写入数据库')
            }

            resolve(body)
          } catch (e) {
            reject()
          }
        }
      })
    })
  } else {
    console.log('调用数据库返回数据')
    return rdata.data[0].data;
  }

}